import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/models/common/parentLetterResult.dart';
import 'package:ichinesereader/models/common/userStatusDto.dart';
import 'package:ichinesereader/models/common/usernameList.dart';
import 'package:ichinesereader/models/school/removeClassStudentDto.dart';
import 'package:ichinesereader/models/school/studentNamesList.dart';
import 'package:ichinesereader/models/student/StudentItem.dart';
import 'package:ichinesereader/pages/schooladmin/addStudentsToClass.dart';
import 'package:ichinesereader/pages/teacher/addStudentsToClass.dart';
import 'package:ichinesereader/pages/teacher/studentdetails.dart';
import 'package:ichinesereader/service/schooladmin.dart';
import 'package:ichinesereader/themes/buttonStyles.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/utils/save_file_mobile.dart';
import 'package:ichinesereader/utils/save_file_web.dart';
import 'package:ichinesereader/widgets/buttons/classSelectionSchoolAdminDropdown.dart';
import 'package:ichinesereader/widgets/dialogs/resetStudentPasswordReactive.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:syncfusion_flutter_datagrid_export/export.dart';
import 'package:syncfusion_flutter_xlsio/xlsio.dart' as xlsio;
import 'package:intl/intl.dart';
import 'package:percent_indicator/percent_indicator.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:toggle_switch/toggle_switch.dart';
import '../dialogs/moveStudentToClassDialog.dart';

// ignore: must_be_immutable
class StudentsDataGrids extends StatelessWidget {
  StudentsDataGrids(this.isSchoolAdmin, this.studentItems, this.showAllClass);

  final GlobalKey<SfDataGridState> studentGridkey =
      GlobalKey<SfDataGridState>();

  List<StudentItem> studentItems;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  bool showAllClass = false;
  bool isSchoolAdmin = true;
  List<DataGridRow> dataGridRows = <DataGridRow>[];
  DataGridController _dataGridController = DataGridController();
  SchoolAdminController _schoolAdminController = Get.find();
  SchoolAdminServiceProvider _adminServiceProvider =
      new SchoolAdminServiceProvider();
  var box = Hive.box('appconfig');
  final UserController _userController = Get.find();
  AppButtonStyles _appButtonStyles = new AppButtonStyles();

  @override
  Widget build(BuildContext context) {
    Log.debug('build StudentsDataGrids');
    var _classId = isSchoolAdmin
        ? _schoolAdminController.currentSchoolAdminClass.classId.toString()
        : _userController.currentClass.value.classId.toString();
    // var _classId = isSchoolAdmin ?
    //     box.get(CacheManagerKey['currentclass'].toString())
    //     : box.get(CacheManagerKey['currentclass'].toString());
    final isSmallScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;

    return Container(
      margin: EdgeInsets.only(bottom: 33.0),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        ////////////上方按钮背景//////////
        Container(
          margin: EdgeInsets.only(bottom: 9.0),
          padding: EdgeInsets.all(
            10.0,
          ),
          width: double.infinity,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(3.0),
            color: Get.isDarkMode
                ? AppTheme.colors.darkTheme2
                : Colors.white.withOpacity(0.3),
          ),
          //上方一排按钮//
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Visibility(
                  visible: isSchoolAdmin,
                  child: Padding(
                    padding: const EdgeInsets.fromLTRB(12.0, 0, 18, 0),
                    child: ClassSelectionDropDownForSchoolAdmin(),
                  )),
              Flexible(
                child: Wrap(
                  alignment: WrapAlignment.end,
                  //crossAxisAlignment: WrapCrossAlignment.end,
                  spacing: 6.0,
                  runSpacing: 4.5,
                  children: [
                    // Visibility(
                    //     visible: isSchoolAdmin,
                    //     child: Padding(
                    //       padding: const EdgeInsets.fromLTRB(12.0, 0, 18, 0),
                    //       child: ClassSelectionDropDownForSchoolAdmin(),
                    //     )),
                    isSchoolAdmin
                        ? ElevatedButton(
                            style: _appButtonStyles.createButtonStyle(),
                            child: Text(
                              'Create'.tr,
                              style: TextStyle(
                                fontFamily: 'Montserrat',
                                color: Get.isDarkMode
                                    ? Colors.black
                                    : Colors.white,
                                fontSize: 15.0,
                              ),
                            ),
                            onPressed: () {
                              Get.to(() => StudentProfileSettingsForTeacher(
                                  studentId: null));
                            })
                        : Visibility(child: Text(''), visible: false),

                    isSchoolAdmin && _classId != 'All'
                        ? ElevatedButton(
                            style: _appButtonStyles.addButtonStyle(),
                            child: Text(
                              'Add'.tr,
                              style: Get.isDarkMode
                                  ? TextStyle(
                                      fontFamily: 'Montserrat',
                                      color: Colors.black,
                                      fontSize: 15.0,
                                    )
                                  : TextStyle(
                                      fontFamily: 'Montserrat',
                                      color:
                                          Theme.of(context).primaryColorLight,
                                    ),
                            ),
                            onPressed: () {
                              Get.to(() => AddStudentsToClassSchoolAdminPage());
                            })
                        : Visibility(child: Text(''), visible: false),
                    isSchoolAdmin == false && _classId != 'All'
                        ? ElevatedButton(
                            style: _appButtonStyles.addButtonStyle(),
                            child: Text(
                              'Add'.tr,
                              style: Get.isDarkMode
                                  ? TextStyle(
                                      fontFamily: 'Montserrat',
                                      color: Colors.black,
                                      // fontFamily: 'Montserrat',
                                      fontSize: 16.0,
                                    )
                                  : TextStyle(
                                      fontFamily: 'Montserrat',
                                      color:
                                          Theme.of(context).primaryColorLight,
                                    ),
                            ),
                            onPressed: () {
                              Get.to(() => AddStudentsToClassPage());
                            })
                        : Visibility(child: Text(''), visible: false),
                    ////////////MOVE BUTTON HERE////////////

                    ElevatedButton(
                        style: _appButtonStyles.removeButtonStyle(),
                        child: Text(
                          _classId == 'All' ? 'Delete' : 'Remove'.tr,
                          style: Get.isDarkMode
                              ? TextStyle(
                                  fontFamily: 'Montserrat',
                                  color: Colors.black,
                                  fontSize: 15.0,
                                )
                              : TextStyle(
                                  fontFamily: 'Montserrat',
                                  color: AppTheme.colors.lightPink,
                                ),
                        ),
                        onPressed: () {
                          if (_dataGridController.selectedRows.length > 0) {
                            var cid = isSchoolAdmin
                                ? _schoolAdminController
                                    .currentSchoolAdminClass.classId
                                    .toString()
                                : _userController.currentClass.value.classId
                                    .toString();
                            if (cid == 'All' && isSchoolAdmin) {
                              var studentsDto = StudentNamesList();
                              List<String>? students = [];
                              _dataGridController.selectedRows.forEach((row) {
                                var uid = row
                                    .getCells()
                                    .where(
                                        (element) => element.columnName == 'Id')
                                    .first
                                    .value;
                                var student = studentItems
                                    .where((e) =>
                                        e.userId.toString() == uid.toString())
                                    .first;
                                students.add(student.userName.toString());
                              });
                              studentsDto.studentsName = students;
                              _schoolAdminController
                                  .deleteStudents(studentsDto)
                                  .then((result) {
                                if (result.status == 1000) {
                                  Get.snackbar(
                                      'Message'.tr, 'Successfully Deleted'.tr,
                                      backgroundColor:
                                          Theme.of(context).primaryColor,
                                      colorText:
                                          Theme.of(context).primaryColorLight,
                                      snackPosition: SnackPosition.BOTTOM);
                                } else {
                                  Get.snackbar(
                                      'Message'.tr, result.message.toString(),
                                      backgroundColor:
                                          Theme.of(context).primaryColor,
                                      colorText:
                                          Theme.of(context).primaryColorLight,
                                      snackPosition: SnackPosition.BOTTOM);
                                }
                              });
                            } else {
                              RemoveClassStudentDto data =
                                  new RemoveClassStudentDto();
                              data.students = [];
                              _dataGridController.selectedRows.forEach((row) {
                                var uid = row
                                    .getCells()
                                    .where(
                                        (element) => element.columnName == 'Id')
                                    .first
                                    .value;
                                var student = studentItems
                                    .where((e) =>
                                        e.userId.toString() == uid.toString())
                                    .first;
                                data.students?.add(student.userName.toString());
                                studentItems.remove(student);
                              });
                              _schoolAdminController
                                  .removeStudentsFromClass(cid, data)
                                  .then((result) {
                                if (result.status == 1000) {
                                  Get.snackbar(
                                      'Message'.tr, 'Successfully Removed'.tr,
                                      backgroundColor:
                                          Theme.of(context).primaryColor,
                                      colorText:
                                          Theme.of(context).primaryColorLight,
                                      snackPosition: SnackPosition.BOTTOM);
                                } else {
                                  Get.snackbar(
                                      'Message'.tr, result.message.toString(),
                                      backgroundColor:
                                          Theme.of(context).primaryColor,
                                      colorText:
                                          Theme.of(context).primaryColorLight,
                                      snackPosition: SnackPosition.BOTTOM);
                                }
                              });
                            }
                          } else {
                            Get.snackbar('Message'.tr,
                                'Please choose at least one student.'.tr,
                                backgroundColor: Theme.of(context).primaryColor,
                                colorText: Theme.of(context).primaryColorLight,
                                snackPosition: SnackPosition.BOTTOM);
                          }
                        }),

                    Visibility(
                        child: ElevatedButton(
                            style: _appButtonStyles.moveButtonStyle(),
                            child: Text(
                              'Move'.tr,
                              style: TextStyle(
                                fontFamily: 'Montserrat',
                                color: Get.isDarkMode
                                    ? Colors.black
                                    : Get.theme.primaryColorLight,
                                fontSize: 15,
                              ),
                            ),
                            onPressed: () {
                              if (_dataGridController.selectedRows.length > 0) {
                                String fromClassId = _schoolAdminController
                                    .currentSchoolAdminClass.classId
                                    .toString();
                                if (fromClassId == 'All') return;
                                List<String>? students = [];
                                _dataGridController.selectedRows.forEach((row) {
                                  var uid = row
                                      .getCells()
                                      .where((element) =>
                                          element.columnName == 'Id')
                                      .first
                                      .value;
                                  var student = studentItems
                                      .where((e) =>
                                          e.userId.toString() == uid.toString())
                                      .first;
                                  students.add(student.userName.toString());
                                });

                                showGeneralDialog(
                                    context: Get.context!,
                                    transitionDuration:
                                        Duration(milliseconds: 400),
                                    pageBuilder: (bc, ania, anis) {
                                      return MoveStudentToClassDialog(
                                          fromClassId: fromClassId,
                                          userNames: students,
                                          completeCallback: () {
                                            Log.debug('completeCallback');
                                            _schoolAdminController
                                                .fetchSchoolStudentsByClassId(
                                                    fromClassId, false);
                                          });
                                    });
                              } else {
                                Get.snackbar('Message'.tr,
                                    'Please choose at least one student.'.tr,
                                    backgroundColor:
                                        Theme.of(context).primaryColor,
                                    colorText:
                                        Theme.of(context).primaryColorLight,
                                    snackPosition: SnackPosition.BOTTOM);
                              }
                            }),
                        visible: isSchoolAdmin),
                    Visibility(
                      visible: !isSmallScreen && GetPlatform.isWeb,
                      child: ElevatedButton(
                        style: _appButtonStyles.exportButtonStyle(),
                        child: Text('Export'.tr,
                            style: Get.isDarkMode
                                ? TextStyle(
                                    fontFamily: 'Montserrat',
                                    color: Colors.black,
                                    fontSize: 15.0,
                                  )
                                : TextStyle(
                                    fontFamily: 'Montserrat',
                                    color: Theme.of(context).primaryColorLight,
                                    fontSize: 15.0,
                                  )),
                        onPressed: () async {
                          final xlsio.Workbook workbook = studentGridkey
                              .currentState!
                              .exportToExcelWorkbook(excludeColumns: ['Id']);
                          final List<int> bytes = workbook.saveAsStream();
                          workbook.dispose();
                          if (GetPlatform.isWeb)
                            await FileSaveHelper.saveAndLaunchFile(
                                bytes, 'students.xlsx');
                          else
                            await FileSaveHelperMobile.saveAndLaunchFile(
                                bytes, 'students.xlsx');
                        },
                      ),
                    ),

                    Visibility(
                      visible: !isSmallScreen && GetPlatform.isWeb,
                      child: ElevatedButton(
                          style: _appButtonStyles.printLetterButtonStyle(),
                          child: Text('Print Parent Letter'.tr,
                              style: Get.isDarkMode
                                  ? TextStyle(
                                      fontFamily: 'Montserrat',
                                      color: Colors.black,
                                      fontSize: 15.0,
                                    )
                                  : TextStyle(
                                      fontFamily: 'Montserrat',
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : Get.theme.primaryColorLight,
                                      fontSize: 15.0,
                                    )),
                          onPressed: () async {
                            UsernameList dto = new UsernameList();
                            dto.userNames = [];
                            for (int i = 0;
                                i < _dataGridController.selectedRows.length;
                                i++) {
                              var row = _dataGridController.selectedRows[i];
                              var uid = row
                                  .getCells()
                                  .where(
                                      (element) => element.columnName == 'Id')
                                  .first
                                  .value;
                              var student = studentItems
                                  .where((e) =>
                                      e.userId.toString() == uid.toString())
                                  .first;
                              if (dto.userNames != null &&
                                  !dto.userNames!
                                      .contains(student.userName.toString())) {
                                dto.userNames!.add(student.userName.toString());
                                //student.disabled = false;
                              }
                            }
                            if (dto.userNames?.length == 0) {
                              Get.snackbar('Message'.tr,
                                  'Please choose at least one student.'.tr,
                                  backgroundColor:
                                      Theme.of(context).primaryColor,
                                  colorText:
                                      Theme.of(context).primaryColorLight,
                                  snackPosition: SnackPosition.BOTTOM);
                              return;
                            }

                            var response = await _adminServiceProvider
                                .createParentLetters(dto);
                            if (response.statusCode == 200) {
                              ParentLetterResult parentletter =
                                  parentLetterResultFromJson(
                                      response.bodyString);
                              if (parentletter.pdfUrl != null &&
                                  parentletter.pdfUrl != '') {
                                launchInWebViewWithJavaScript(
                                    parentletter.pdfUrl.toString());
                              }
                            } else {
                              Get.snackbar('Message'.tr,
                                  'Failed to print parent letters'.tr,
                                  backgroundColor:
                                      Theme.of(context).primaryColor,
                                  colorText:
                                      Theme.of(context).primaryColorLight,
                                  snackPosition: SnackPosition.BOTTOM);
                            }
                          }),
                    ),

                    Visibility(
                      visible: !isSmallScreen && GetPlatform.isWeb,
                      child: ElevatedButton(
                          //debounceTimeMs: 1500,
                          style: _appButtonStyles.printCardButtonStyle(),
                          child: Text(
                            'Print Login Cards'.tr,
                            style: TextStyle(
                              fontFamily: 'Montserrat',
                              color: Get.isDarkMode
                                  ? Colors.black
                                  : Theme.of(context).primaryColorLight,
                              fontSize: 15.0,
                            ),
                          ),
                          onPressed: () async {
                            var classId = isSchoolAdmin
                                ? _schoolAdminController
                                    .currentSchoolAdminClass.classId
                                    .toString()
                                : _userController.currentClass.value.classId
                                    .toString();

                            if (classId != 'All') {
                              _adminServiceProvider
                                  .createClassLoginCards(classId)
                                  .then((response) {
                                if (response.statusCode == 200) {
                                  ParentLetterResult parentletter =
                                      parentLetterResultFromJson(
                                          response.bodyString);
                                  if (parentletter.pdfUrl != null &&
                                      parentletter.pdfUrl != '') {
                                    launchInWebViewWithJavaScript(
                                        parentletter.pdfUrl.toString());
                                  }
                                } else {
                                  Get.snackbar('Message'.tr,
                                      'Failed to print class login cards'.tr,
                                      backgroundColor:
                                          Theme.of(context).primaryColor,
                                      colorText:
                                          Theme.of(context).primaryColorLight,
                                      snackPosition: SnackPosition.BOTTOM);
                                }
                              });
                            }
                          }),
                    ),

                    isSchoolAdmin && GetPlatform.isWeb
                        ? ElevatedButton(
                            style: _appButtonStyles.enableButtonStyle(),
                            child: Text(
                              'Enable'.tr,
                              style: TextStyle(
                                fontFamily: 'Montserrat',
                                color: Get.isDarkMode
                                    ? Colors.black
                                    : Get.theme.primaryColorLight,
                                fontSize: 15,
                              ),
                            ),
                            onPressed: () async {
                              UserStatusDto dto = new UserStatusDto();
                              dto.enable = true;
                              dto.userNames = [];
                              for (int i = 0;
                                  i < _dataGridController.selectedRows.length;
                                  i++) {
                                var row = _dataGridController.selectedRows[i];
                                var uid = row
                                    .getCells()
                                    .where(
                                        (element) => element.columnName == 'Id')
                                    .first
                                    .value;
                                var student = studentItems
                                    .where((e) =>
                                        e.userId.toString() == uid.toString())
                                    .first;
                                if (dto.userNames != null &&
                                    !dto.userNames!.contains(
                                        student.userName.toString())) {
                                  dto.userNames!
                                      .add(student.userName.toString());
                                }
                              }
                              _schoolAdminController
                                  .updateStudentsStatus(dto)
                                  .then((statusMessage) {
                                if (statusMessage.status == 1000) {
                                  Get.snackbar(
                                      'Message'.tr, 'Successfully Updated'.tr,
                                      backgroundColor:
                                          Theme.of(context).primaryColor,
                                      colorText:
                                          Theme.of(context).primaryColorLight,
                                      snackPosition: SnackPosition.BOTTOM);
                                }
                              });
                            })
                        : Visibility(child: Text(''), visible: false),
                    isSchoolAdmin && GetPlatform.isWeb
                        ? ElevatedButton(
                            style: _appButtonStyles.disableButtonStyle(),
                            child: Text(
                              'Disable'.tr,
                              style: TextStyle(
                                color: Get.isDarkMode
                                    ? Colors.black
                                    : Get.theme.primaryColorLight,
                              ),
                            ),
                            onPressed: () async {
                              UserStatusDto dto = new UserStatusDto();
                              dto.enable = false;
                              dto.userNames = [];
                              for (int i = 0;
                                  i < _dataGridController.selectedRows.length;
                                  i++) {
                                var row = _dataGridController.selectedRows[i];
                                var uid = row
                                    .getCells()
                                    .where(
                                        (element) => element.columnName == 'Id')
                                    .first
                                    .value;
                                var student = studentItems
                                    .where((e) =>
                                        e.userId.toString() == uid.toString())
                                    .first;
                                if (dto.userNames != null &&
                                    !dto.userNames!
                                        .contains(student.userName)) {
                                  dto.userNames!.add(student.userName!);
                                }
                              }
                              _schoolAdminController
                                  .updateStudentsStatus(dto)
                                  .then((statusMessage) {
                                if (statusMessage.status == 1000) {
                                  Get.snackbar(
                                      'Message'.tr, 'Successfully Updated'.tr,
                                      backgroundColor:
                                          Theme.of(context).primaryColor,
                                      colorText:
                                          Theme.of(context).primaryColorLight,
                                      snackPosition: SnackPosition.BOTTOM);
                                }
                              });
                            })
                        : Visibility(child: Text(''), visible: false),
                  ],
                ),
              ),
            ],
          ),
        ),
        Expanded(child: _buildDataGrid()),
      ]),
    );
  }

  Container _buildDataGrid() {
    if (GetPlatform.isDesktop || GetPlatform.isWeb) isWebOrDesktop = true;
    return Container(
      decoration: BoxDecoration(
          color: Get.isDarkMode
              ? AppTheme.colors.darkTheme2
              : Colors.white.withOpacity(0.3),
          borderRadius: BorderRadius.circular(3.0)),
      child: Container(
        margin: EdgeInsets.all(12.0),
        decoration: BoxDecoration(
          color: Get.isDarkMode ? AppTheme.colors.darkTheme2 : Colors.white,
          borderRadius: BorderRadius.circular(3.0),
        ),
        child: Container(
          child: SfDataGrid(
            source: StudentDataGridSource(items: studentItems),
            isScrollbarAlwaysShown: true,
            onQueryRowHeight: (row) {
              return row.rowIndex == 0 ? 50.0 : 49.0;
            },
            //设置表头高度
            key: studentGridkey,
            allowFiltering: true,
            showCheckboxColumn: true,
            checkboxColumnSettings: Get.isDarkMode
                ? DataGridCheckboxColumnSettings(
                    backgroundColor: AppTheme.colors.darkTheme4)
                : DataGridCheckboxColumnSettings(
                    backgroundColor: Colors.blue[50]),
            onSelectionChanged:
                (List<DataGridRow> addedRows, List<DataGridRow> removedRows) {
              Log.debug(_dataGridController.selectedRows.length.toString());
              List<StudentItem> selected = [];
              if (_dataGridController.selectedRows.isNotEmpty) {
                _dataGridController.selectedRows.forEach((row) {
                  var uid = row
                      .getCells()
                      .where((element) => element.columnName == 'Id')
                      .first
                      .value;
                  var student = studentItems
                      .where((e) => e.userId.toString() == uid.toString())
                      .first;
                  selected.add(student);
                });
              }
              if (selected.length > 0)
                _schoolAdminController.addStudentToSelectedList(selected);
            },
            rowsPerPage: 15,
            allowSorting: true,
            allowTriStateSorting: true,
            allowSwiping: true,
            selectionMode: SelectionMode.multiple,
            navigationMode: GridNavigationMode.row,
            controller: _dataGridController,
            endSwipeActionsBuilder:
                (BuildContext context, DataGridRow row, int rowIndex) {
              return GestureDetector(
                  onTap: () {
                    RemoveClassStudentDto data = new RemoveClassStudentDto();
                    data.students = [];
                    var uid = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    var student = studentItems
                        .where((e) => e.userId.toString() == uid.toString())
                        .first;
                    data.students?.add(student.userName.toString());

                    var cid = isSchoolAdmin
                        ? _schoolAdminController.currentSchoolAdminClass.classId
                            .toString()
                        : _userController.currentClass.value.classId.toString();

                    _schoolAdminController.removeStudentsFromClass(cid, data);

                    Get.snackbar('Message'.tr, 'Successfully Removed'.tr,
                        backgroundColor: Get.theme.primaryColor,
                        colorText: Get.theme.primaryColorLight,
                        snackPosition: SnackPosition.BOTTOM);
                  },
                  child: Container(
                      color: Colors.redAccent,
                      child: Center(
                        child: Icon(Icons.delete),
                      )));
            },
            columns: <GridColumn>[
              GridColumn(
                columnName: 'UserName',
                width: isWebOrDesktop ? 190 : 160,
                label: buildDataGridColumnLabel('UserName'),
              ),
              GridColumn(
                width: 160,
                columnName: 'FirstName',
                label: buildDataGridColumnLabel('FirstName'),
              ),
              GridColumn(
                columnName: 'LastName',
                width: 160,
                label: buildDataGridColumnLabel('LastName'),
              ),
              GridColumn(
                columnName: 'Password',
                allowFiltering: false,
                width: isWebOrDesktop ? 120 : 120,
                label: buildDataGridColumnLabel('Password'),
              ),
              GridColumn(
                columnName: 'Class',
                width: isWebOrDesktop ? 180 : 180,
                visible: showAllClass ? true : false,
                //visible: false,
                label: buildDataGridColumnLabel('Class'),
              ),
              GridColumn(
                columnName: 'Level',
                width: isWebOrDesktop ? 100 : 100,
                allowFiltering: false,
                label: buildDataGridColumnLabel('Level'),
              ),
              GridColumn(
                columnName: 'LevelPercentage',
                width: isWebOrDesktop ? 180 : 180,
                allowFiltering: false,
                label: buildDataGridColumnLabel('LevelPercentage'),
              ),
              GridColumn(
                columnName: 'Enabled',
                allowFiltering: false,
                visible: isSchoolAdmin ? true : false,
                width: isWebOrDesktop ? 160 : 120,
                label: buildDataGridColumnLabel('Enabled?'),
              ),
              GridColumn(
                columnName: 'Incentive',
                allowFiltering: false,
                visible: isSchoolAdmin ? false : true,
                width: isWebOrDesktop ? 160 : 130,
                label: buildDataGridColumnLabel('Incentive?'),
              ),
              GridColumn(
                columnName: 'LastLogin',
                allowFiltering: false,
                width: isWebOrDesktop ? 180 : 150,
                label: buildDataGridColumnLabel('LastLogin'),
              ),
              GridColumn(
                columnName: 'Id',
                allowFiltering: false,
                width: 10,
                visible: false,
                label: buildDataGridColumnLabel('Id'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class StudentDataGridSource extends DataGridSource {
  StudentDataGridSource({required List<StudentItem> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'UserName', value: dataGridRow.userName),
              DataGridCell<String>(
                  columnName: 'FirstName', value: dataGridRow.firstName),
              DataGridCell<String>(
                  columnName: 'LastName', value: dataGridRow.lastName),
              DataGridCell<String>(columnName: 'Password', value: 'Change'),
              DataGridCell<String>(
                  columnName: 'Class',
                  value: dataGridRow.classNames != null
                      ? json.encode(dataGridRow.classNames)
                      : null),
              DataGridCell<String>(
                  columnName: 'Level', value: dataGridRow.level),
              DataGridCell<int>(
                  columnName: 'LevelPercentage',
                  value: dataGridRow.levelPercentage),
              DataGridCell<bool>(
                  columnName: 'Enabled',
                  value: dataGridRow.disabled == true ? false : true),
              DataGridCell<bool>(
                  columnName: 'Incentive',
                  value: dataGridRow.gameDisable == true ? false : true),
              DataGridCell<int>(
                  columnName: 'LastLogin', value: dataGridRow.lastLoggedIn),
              DataGridCell<String>(columnName: 'Id', value: dataGridRow.id),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];
  SchoolAdminController _schoolAdminController = Get.find();

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'Class') {
            var tempstr = '';
            if (dataGridCell.value != null &&
                dataGridCell.value.toString().contains("]")) {
              List<String> items =
                  List<String>.from(json.decode(dataGridCell.value.toString()));
              items.forEach((element) {
                tempstr = tempstr + element.toString() + ',';
              });
              tempstr = tempstr.substring(0, tempstr.length - 1);
            } else {
              tempstr = dataGridCell.value != null
                  ? dataGridCell.value.toString().replaceAll("\"", "")
                  : '';
            }
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 15.0),
                child: Text(
                  tempstr,
                  softWrap: true,
                  maxLines: 2,
                  overflow: TextOverflow.fade,
                ));
          } else if (dataGridCell.columnName == 'UserName') {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 15.0),
                child: GestureDetector(
                  onTap: () {
                    var userId = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    Get.to(() =>
                        StudentProfileSettingsForTeacher(studentId: userId));
                  },
                  child: Text(
                    dataGridCell.value.toString(),
                    style: Get.textTheme.titleLarge,
                    //style: TextStyle(color: Colors.blue[300], ),
                    overflow: TextOverflow.fade,
                  ),
                ));
          } else if (dataGridCell.columnName == 'Password') {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 15.0),
                child: GestureDetector(
                  onTap: () {
                    var userName = row
                        .getCells()
                        .where((element) => element.columnName == 'UserName')
                        .first
                        .value;

                    showGeneralDialog(
                        context: Get.context!,
                        transitionDuration: Duration(milliseconds: 400),
                        pageBuilder: (bc, ania, anis) {
                          return ResetStudentPasswordReactiveDialog(
                              userName: userName);
                          // ResetStudentPasswordDialog(
                          //     userName: userName);
                        });
                  },
                  child: Text(
                    dataGridCell.value.toString(),
                    style: Get.textTheme.titleLarge,
                    overflow: TextOverflow.fade,
                  ),
                ));
          } else if (dataGridCell.columnName == 'LevelPercentage') {
            int process = dataGridCell.value ?? 0;
            return Container(
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: 8.0),
              child: LinearPercentIndicator(
                animation: true,
                lineHeight: 18.0,
                animationDuration: 1000,
                percent: process.toDouble() / 100,
                center: Text(
                  "$process%",
                  style: TextStyle(
                    fontSize: 12.0,
                    color: Get.isDarkMode
                        ? Colors.black
                        : Colors.black.withOpacity(0.6),
                  ),
                ),
                progressColor: Get.isDarkMode
                    ? AppTheme.colors.primaryLight.withOpacity(0.9)
                    : AppTheme.colors.addBtn.withOpacity(0.6),
                barRadius: Radius.circular(12),
                backgroundColor: Get.isDarkMode
                    ? Get.theme.primaryColor.withOpacity(0.9)
                    : Colors.black.withOpacity(0.1),
              ),
            );
          } else if (dataGridCell.columnName == 'LastLogin') {
            if (dataGridCell.value > 0) {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 15.0),
                  child: Text(
                    DateFormat('MM/dd/yyyy kk:mm').format(
                        DateTime.fromMillisecondsSinceEpoch(
                            dataGridCell.value)),
                    overflow: TextOverflow.fade,
                    style: Get.textTheme.bodySmall,
                  ));
            } else {
              return Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 15.0),
                  child: Text(
                    ' - ',
                    overflow: TextOverflow.fade,
                  ));
            }
          } else if (dataGridCell.columnName == 'Enabled') {
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 2.0),
              child: ToggleSwitch(
                customWidths: [55.0, 40.0],
                minHeight: 25,
                cornerRadius: 20.0,
                // activeBgColors: [
                //   [Get.theme.primaryColorDark],
                //   [Get.theme.primaryColorDark]
                // ],
                activeFgColor: Get.isDarkMode
                    ? Get.theme.primaryColorDark
                    : Get.theme.primaryColorLight,
                inactiveBgColor: AppTheme.colors.disableBtnLight,
                inactiveFgColor: AppTheme.colors.disableBtn,
                totalSwitches: 2,
                initialLabelIndex: dataGridCell.value ? 0 : 1,
                labels: ['Yes', ''],
                icons: [null, Icons.disabled_by_default_rounded],
                onToggle: (index) {
                  //Log.debug('switched to: $index');
                  UserStatusDto dto = new UserStatusDto();
                  dto.enable = index == 0 ? true : false;
                  dto.userNames = [];
                  var username = row
                      .getCells()
                      .where((element) => element.columnName == 'UserName')
                      .first
                      .value;
                  dto.userNames!.add(username);
                  _schoolAdminController.updateStudentsStatus(dto);
                },
              ),
              //Text(dataGridCell.value.toString()),
              // GFToggle(
              //   value: dataGridCell.value,
              //   // enabledText: 'Enabled',
              //   // disabledText: 'Disabled',
              //   onChanged: (val) {
              //     UserStatusDto dto = new UserStatusDto();
              //     dto.enable = val;
              //     dto.userNames = [];
              //     var username = row
              //         .getCells()
              //         .where((element) => element.columnName == 'UserName')
              //         .first
              //         .value;
              //     dto.userNames!.add(username);
              //     _schoolAdminController.updateStudentsStatus(dto);
              //   },
              //   type: GFToggleType.ios,
              // ),
            );
          } else if (dataGridCell.columnName == 'Incentive') {
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 2.0),
              child: ToggleSwitch(
                fontSize: 9.0,
                customWidths: [55.0, 40.0],
                minHeight: 25,
                cornerRadius: 20.0,
                activeBgColors: Get.isDarkMode
                    ? [
                        [Get.theme.primaryColorDark],
                        [Get.theme.primaryColorDark]
                      ]
                    : [
                        [Get.theme.primaryColor],
                        [Get.theme.primaryColor]
                      ],
                activeFgColor: Get.isDarkMode
                    ? (Colors.black)
                    : Get.theme.primaryColorLight,
                inactiveBgColor: Get.isDarkMode
                    ? Get.theme.primaryColor
                    : AppTheme.colors.disableBtnLight,
                inactiveFgColor:
                    Get.isDarkMode ? Colors.black : Colors.blueGrey,
                totalSwitches: 2,
                initialLabelIndex: dataGridCell.value ? 0 : 1,
                labels: ['YES', ''],
                icons: [null, Icons.disabled_by_default_rounded],
                onToggle: (index) {
                  //Log.debug('switched to: $index');
                  bool disabled = index == 1 ? true : false;
                  var username = row
                      .getCells()
                      .where((element) => element.columnName == 'UserName')
                      .first
                      .value;
                  _schoolAdminController.updateStudentIncentive(
                      username, disabled);
                },
              ),
              // GFToggle(
              //   value: dataGridCell.value,
              //   onChanged: (val) {

              //     bool disabled = val == true ? false : true;
              //     var username = row
              //         .getCells()
              //         .where((element) => element.columnName == 'UserName')
              //         .first
              //         .value;
              //     _schoolAdminController.updateStudentIncentive(
              //         username, disabled);
              //   },
              //   type: GFToggleType.ios,
              // ),
            );
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 15.0),
                child: Text(
                  dataGridCell.value.toString(),
                  overflow: TextOverflow.fade,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
